package com.example.mdc.logback.module.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;


/**
 * @author:      liu_pc
 * Date:        2023/8/7
 * Description: HelloService
 * Version: 1.0
 */
@Service
public class HelloAsyncService {

    private final Logger logger = LoggerFactory.getLogger(HelloAsyncService.class);

    private final Executor executor;

    private final static int SIMULATE_THREAD_SIZE = 5;

    public HelloAsyncService(@Qualifier("ownThreadPoolExecutor") Executor executor) {
        this.executor = executor;
    }

    /**
     * 使用异步数据测试打印日志
     *
     * @param param 请求参数
     */
    public void helloAsync(String param) {

        logger.info("helloAsync 开始执行异步操作,请求参数:{}", param);
        List<Integer> simulateThreadList = new ArrayList<>(5);
        for (int i = 0; i <= SIMULATE_THREAD_SIZE; i++) {
            simulateThreadList.add(i);
        }
        for (Integer thread : simulateThreadList) {
            Map<String, String> mainMdcContext = MDC.getCopyOfContextMap();
            CompletableFuture.runAsync(() -> {
                try {
                    MDC.setContextMap(mainMdcContext);
                    //模拟其他业务逻辑处理耗时
                    Thread.sleep(1000);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                logger.info("threadIndex:{} Another thread running", thread);
            }, executor);
        }
    }
}
